package cn.edu.scnu.semart.user.controller;

import cn.edu.scnu.semart.common.result.Result;
import cn.edu.scnu.semart.common.utils.MD5;
import cn.edu.scnu.semart.common.utils.UserContext;
import cn.edu.scnu.semart.model.user.User;
import cn.edu.scnu.semart.user.service.UserService;
import cn.edu.scnu.semart.vo.user.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * 用户管理 前端控制器
 */
@RestController
@RequestMapping("/admin/user")
@Api(tags = "用户管理")
public class UserController {

    @Resource
    private UserService userService;

    @ApiOperation(value = "获取用户分页列表")
    @GetMapping("{page}/{limit}")
    public Result index(
            @ApiParam(name = "page", value = "当前页码", required = true)
            @PathVariable Long page,

            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable Long limit,

            @ApiParam(name = "userQueryVo", value = "查询对象", required = false)
            UserQueryVo userQueryVo) {
        Page<User> pageParam = new Page<>(page, limit);
        IPage<User> pageModel = userService.selectPage(pageParam, userQueryVo);
        return Result.ok(pageModel);
    }

    @ApiOperation(value = "获取用户详情")
    @GetMapping("get/{id}")
    public Result get(@PathVariable Long id) {
        User user = userService.getById(id);
        return Result.ok(user);
    }

    @ApiOperation(value = "注册用户")
    @PostMapping("save")
    public Result save(@Valid @RequestBody UserRegisterVo vo) {
        User user = new User();
        BeanUtils.copyProperties(vo,user);
        user.setUserType(User.UserType.valueOf(vo.getUserType().toUpperCase()));
//        user.setUserType(User.UserType.NORMAL);
        user.setStatus(User.UserStatus.ACTIVE);
        user.setCreatedAt(new Date());
        user.setUpdatedAt(new Date());
        // 在serviceimpl对密码进行MD5加密
        user.setPassword(user.getPassword());
        userService.save(user);
        return Result.ok(null);
    }

    @ApiOperation(value = "修改个人信息")
    @PutMapping("update")
    public Result updateById(@Valid @RequestBody UserProfileUpdateVo vo, HttpServletRequest request) {
        Integer userId = UserContext.getUserId(request);
        userService.updateProfile(userId,vo);
//        userService.updateById(user);
//        user.setUpdatedAt(new Date());
        return Result.ok(null);
    }

//    @ApiOperation(value = "删除用户")
//    @DeleteMapping("remove/{id}")
//    public Result remove(@PathVariable Long id,@RequestAttribute("currentUserType") String currentUserType) {
//        if(!"ADMIN".equalsIgnoreCase(currentUserType)){
//            return Result.fail("无权限操作");
//        }
//        userService.removeById(id);
//        return Result.ok(null);
//    }
    @ApiOperation(value = "删除用户")
    @DeleteMapping("remove/{id}")
    public Result remove(@PathVariable Long id, HttpServletRequest request) {
        if(!"ADMIN".equalsIgnoreCase(UserContext.getUserType( request))){
            return Result.fail("无权限操作");
        }
        userService.removeById(id);
        return Result.ok(null);
    }

//    @ApiOperation(value = "批量删除用户")
//    @DeleteMapping("batchRemove")
//    public Result batchRemove(@RequestBody List<Long> idList,@RequestAttribute("currentUserType") String currentUserType) {
//        if(!"ADMIN".equalsIgnoreCase(currentUserType)){
//            return Result.fail("无权限操作");
//        }
//        userService.removeByIds(idList);
//        return Result.ok(null);
//    }
    @ApiOperation(value = "批量删除用户")
    @DeleteMapping("batchRemove")
    public Result batchRemove(@RequestBody List<Long> idList,HttpServletRequest request) {
        if(!"ADMIN".equalsIgnoreCase(UserContext.getUserType( request))){
            return Result.fail("无权限操作");
        }
        userService.removeByIds(idList);
        return Result.ok(null);
    }

//    @PostMapping("/resetPwd")
//    @ApiOperation("管理员重置用户密码")
//    public Result resetPwd(@Valid @RequestBody AdminResetPwdVo vo,@RequestAttribute("currentUserType") String currentUserType) {
//        if(!"ADMIN".equalsIgnoreCase(currentUserType)){
//            return Result.fail("无权限操作");
//        }
//        userService.resetPassword(vo.getUserId(), vo.getNewPassword());
////        System.out.println("管理员重置的密码"+vo.getNewPassword());
//        return Result.ok(null);
//    }
    @PostMapping("/resetPwd")
    @ApiOperation("管理员重置用户密码")
    public Result resetPwd(@Valid @RequestBody AdminResetPwdVo vo,HttpServletRequest request) {
        if(!"ADMIN".equalsIgnoreCase(UserContext.getUserType(request))){
            return Result.fail("无权限操作");
        }
        userService.resetPassword(vo.getUserId(), vo.getNewPassword());
//        System.out.println("管理员重置的密码"+vo.getNewPassword());
        return Result.ok(null);
    }

//    //解封/封禁
//    @PostMapping("/ban/{id}")
//    public Result ban(@PathVariable Long id,
//                      @RequestAttribute("currentUserType") String type) {
//        if (!"ADMIN".equalsIgnoreCase(type)) return Result.fail("无权限");
//        userService.updateStatus(id, User.UserStatus.BANNED);
//        return Result.ok(null);
//    }
    //解封/封禁
    @PostMapping("/ban/{id}")
    public Result ban(@PathVariable Long id,
                      HttpServletRequest request) {
        if (!"ADMIN".equalsIgnoreCase(UserContext.getUserType(request))) return Result.fail("无权限");
        System.out.println("权限"+UserContext.getUserType(request));
        userService.updateStatus(id, User.UserStatus.BANNED);
        return Result.ok(null);
    }

//    @PostMapping("/unban/{id}")
//    public Result unban(@PathVariable Long id,
//                        @RequestAttribute("currentUserType") String type) {
//        if (!"ADMIN".equalsIgnoreCase(type)) return Result.fail("无权限");
//        userService.updateStatus(id, User.UserStatus.ACTIVE);
//        return Result.ok(null);
//    }
    @PostMapping("/unban/{id}")
    public Result unban(@PathVariable Long id,
                        HttpServletRequest request) {
        if (!"ADMIN".equalsIgnoreCase(UserContext.getUserType(request))) return Result.fail("无权限");
        userService.updateStatus(id, User.UserStatus.ACTIVE);
        return Result.ok(null);
    }

//    //批量解封/封禁
//    @PostMapping("/batch/ban")
//    public Result batchBan(@RequestBody List<Long> ids,
//                           @RequestAttribute("currentUserType") String type) {
//        if (!"ADMIN".equalsIgnoreCase(type)) return Result.fail("无权限");
//        userService.batchUpdateStatus(ids, User.UserStatus.BANNED);
//        return Result.ok(null);
//    }
    //批量解封/封禁
    @PostMapping("/batch/ban")
    public Result batchBan(@RequestBody List<Long> ids,
                          HttpServletRequest request) {
        if (!"ADMIN".equalsIgnoreCase(UserContext.getUserType(request))) return Result.fail("无权限");
        userService.batchUpdateStatus(ids, User.UserStatus.BANNED);
        return Result.ok(null);
    }

//    @PostMapping("/batch/unban")
//    public Result batchUnBan(@RequestBody List<Long> ids,
//                           @RequestAttribute("currentUserType") String type) {
//        if (!"ADMIN".equalsIgnoreCase(type)) return Result.fail("无权限");
//        userService.batchUpdateStatus(ids, User.UserStatus.ACTIVE);
//        return Result.ok(null);
//    }
    @PostMapping("/batch/unban")
    public Result batchUnBan(@RequestBody List<Long> ids,
                          HttpServletRequest request) {
        if (!"ADMIN".equalsIgnoreCase(UserContext.getUserType(request))) return Result.fail("无权限");
        userService.batchUpdateStatus(ids, User.UserStatus.ACTIVE);
        return Result.ok(null);
    }
}